
layui.define(['config', 'admin', 'layer', 'laytpl', 'element', 'form'], function (exports) {
	var server = {

		host: window.location.protocol + "//" + location.host + "/",



		getRootPath_dc: function () {
			var pathName = window.location.pathname.substring(1);
			var webName = pathName == '' ? '' : pathName.substring(0, pathName.indexOf('/'));
			if (webName == "") {
				return window.location.protocol + '//' + window.location.host;
			} else {
				return window.location.protocol + '//' + window.location.host + '/' + webName;
			}
		},

		Stack: {
			push: function (element) {
				server.items.push(element)
			},
			pop: function () {
				return server.items.pop()
			},
			peek: function () {
				return server.items[server.items.length - 1]
			},
			getlast: function () {
				if (server.items.length < 2) return null;
				return server.items[server.items.length - 2]
			},
			isEmpty: function () {
				return server.items.length === 0
			},
			size: function () {
				return server.items.length
			},
			clear: function () {
				server.items = []
			},
			print: function () {
				console.log(server.items.toString())
			},
		},

		formLoad: function (form, data) {
			if (!data || !form) {
				return;
			}

			for (var name in data) {
				// console.log(name)
				var element = $(form + ' [name^=' + name + ']');

				if (!element || element.length == 0) {
					//	element = $(form).find("*[data-name]");

					if (!element || element.length == 0) continue;
				}
				//  console.log(element)

				var attr = $(element).attr("type");
				if (!attr) {
					if ($(element).get(0)) {
						if ($(element).get(0).tagName == 'SELECT') {
							attr = 'select';
						}
					}

				}

				switch (attr) {
					case 'hidden':
					case 'text':
					case 'select':
					case 'number':
						$(element).val(data[name]);
						break;
					case 'checkbox':
						var values = data[name].toString().split(',');
						for (var v in values) {
							var element = $(form + ' [name^=' + name + '][value=' + values[v] + ']');
							$(element).attr('checked', 'checked');
						}
						break;
					case 'radio':
						$(form + ' [name = ' + name + '][value=' + data[name] + ']').next().find("i").click();
						$(form + ' [name = ' + name + '][value=' + data[name] + ']').click();
						break;
					default :
						$(element).val(data[name]);
						break;
				}
			}
		},

		loadData: function (element, data) {
			if (!element || !data) return;

			function getval(e, d, name) {

				var n = $(e).attr(name);
				if (!n) return;
				var regexjj = new RegExp(`(\\'|\\")(.*?)(\\'|\\")`);
				if (checkreg(n, regexjj)) return n;
				var not = n.indexOf("!");
				if (not == 0) n = n.substring(1);
				var data1 = cval(d, n);
				if (not == 0) {
					return !data1;
				} else {
					return (data1 == null || data1 == undefined) ? '' : data1;
				}

			}

			function cval(d, name) {
				if (!name || !d) return null;
				if (name.indexOf(".") == -1) return d[name];
				if (d[name.split(".")[0]]) return cval(d[name.split(".")[0]], name.replace(name.split(".")[0] + ".", ""))
			}


			function setval(e, v) {
				// console.log(e.tagName);
				switch (e.tagName) {
					case 'IMG':
					case 'IMAGE':
						if (v) $(e).attr("src", v);
						break;
					case 'TEXTAREA':
						// console.log("1:"+e.tagName);
						// console.log(e);
						// console.log(v);
						$(e).val(v);
						break;
					case 'INPUT':
						var attr = $(e).attr("type");
						switch (attr) {
							case 'checkbox':
								if (v == null && v == undefined) break;
								var values = v.toString().split(',');
								// if(v){
								// 	$(e)[0].attr('checked','checked');
								// }else{
								// 	$(e).removeAttr("checked")
								// }
								for (var val in values) {
									var ement = $(e).find('*[value=' + values[val] + ']');
									$(ement)[0].attr('checked', 'checked');
								}
								break;
							case 'radio':
								$(e).find('*[value=' + v + ']').next().find("i").click();
								if (v == $(e).val()) $(e).click();
								$(e).find('*[value=' + v + ']').click();

								break;
							default :
								$(e).val(v);
								break;
						}

						break;
					case 'select':
						$(e).val(v);
						break;
					default :
						$(e).text(v);
						break;
				}
			}

			function countvalue(cal, v1, v2) {
				switch (cal) {
					case '+':
						return (isNumber(v1) && isNumber(v2)) ? v1 + v2 : (v1 + "" + v2);
						break;
					case "-":
						return v1 - v2;
						break;
					case "*":
						return v1 * v2;
						break;
					case "/":
						return v1 / v2;
						break;
					case "!":
						return v1 != v2;
						break;
					case '=':
						// console.log("=")
						// console.log(v1);
						// console.log(v2)
						return v1 == v2;
						break;
					case "&":
						// console.log("e")
						// console.log(v1);
						// console.log(v2)
						return v1 && v2;
						break;
					case "|":

						return v1 || v2;
						break;


				}
			}

			function checkval(name, d) {
				if (!name) return;
				var regexCheck = new RegExp(".*(\\&|\\||\\=|\\!|\\*|\\/|\\+|\\-).*");
				var regexjj = new RegExp(`(\\'|\\")(.*?)(\\'|\\")`);
				if (checkreg(name, regexjj)) name = changeStr(name);
				var cal = checkreg(name, regexCheck);
				name = (typeof name === 'string') ? name.trim() : name;
				//if((typeof name === 'string'&& checkreg(name.html(),regexjj)))console.log(server.getStr(name.html(),`(\\'|\\")`, `(\\'|\\")`,2));
				if (!cal) return (isNumber(name)) ? name : ((typeof name === 'string' && checkreg(name.html(), regexjj)) ? server.trim(server.getStr(name.html(), `(\\'|\\")`, `(\\'|\\")`, 2)) : server.trim(cval(d, name.html())));
				var i = name.indexOf(cal);
				var ns1 = name.substring(0, i);
				var j = cal == "&" ? 5 : 1;
				var ns2 = name.substring(i + j);
				if (ns2.indexOf(cal) == 0) ns2 = ns2.substring(j);
				// console.log(ns2);
				var cvalue = countvalue(cal, checkval(ns1, d), checkval(ns2, d));   //  cal=="+"?(v1+v2):(cal=="|"?v1||v2:(v1+cal+v2))  ;
				//console.log(cvalue);
				return cvalue;
			}

			function changeStr(str) {
				var result = str.match(new RegExp(`(\\'|\\")(.*?)(\\'|\\")`, 'g'));
				var r = "";
				if (result)
					result.forEach(function (e) {
						//  console.log(e);
						str = str.replace(e, e.html(1));
					})
				return str;
			}

			function checkreg(str, reg) {
				let res = str.match(reg);

				return res ? res[1] : null
			}

			function isNumber(val) {
				var regPos = /^\d+(\.\d+)?$/;
				var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
				if (regPos.test(val) || regNeg.test(val)) {
					return true;
				} else {
					return false;
				}
			}


			var elem = $(element).find("*[data-for]");
			if (elem && elem.length > 0) {
				for (var i = 0; i < elem.length; i++) {
					var html = "";
					var v = getval(elem[i], data, "data-for");
					if (v == null || v == undefined) continue;
					var inner;
					var vname = $(elem[i]).attr("data-for");
					if (server.getCache(window.location.hash + "_" + element + "_" + vname)) {
						inner = server.getCache(window.location.hash + "_" + element + "_" + vname);
					} else {
						//console.log($(elem[i]).parent())
						var $elem = $(elem[i]);
						// $elem.css("display","block");
						inner = $elem.html().html(1);
						server.setCache(window.location.hash + "_" + element + "_" + vname, inner);
					}

					var jqinnel = $("<div>" + inner.html() + "</div>").get(0);
					var eitem = $(jqinnel).find("*[data-item]");
					//	var eitem= $(elem[i]).find("*[data-item]");
					for (var z = 0; z < v.length; z++) {
						for (var j = 0; j < eitem.length; j++) {
							var v1 = getval(eitem[j], v[z], "data-item");
							setval(eitem[j], v1);
						}
						// console.log(jqinnel)
						if (!jqinnel || !jqinnel.innerHTML) continue;
						//$(jqinnel).show();
						var inner = jqinnel.innerHTML.html(1);
						var n = server.getStr(inner, "{{", "}}")
						while (n) {
							var val = checkval(n.html(), v[z]);
							val = (typeof val == 'string') ? val.html(1) : val;
							var reg = new RegExp("{{" + n + "}}");

							inner = inner.replace(reg, val);
							n = server.getStr(inner, "{{", "}}");
						}
						html += inner.html();
					}
					$(elem[i]).html(html);

				}

			}

			elem = $(element).find("*[data-name]");
			if (elem && elem.length > 0) {
				//	console.log(elem)
				for (var i = 0; i < elem.length; i++) {
					//	 console.log(elem[i])
					var v = getval(elem[i], data, "data-name");
					if (v == null || v == undefined) continue;
					setval(elem[i], v);
				}
			}
			elem = $(element).find("*[data-if]");

			if (elem && elem.length > 0) {
				for (var i = 0; i < elem.length; i++) {
					var v = getval(elem[i], data, "data-if");


					v = (v && v != "'false'" && v != '"false"' && v != "false" && v != "null" && v != "0" && v != "undefined" && v != "'null'" && v != "'0'" && v != "'undefined'") ? $(elem[i]).show() : $(elem[i]).remove();
				}
			}
		},


		formClear: function (form) {
			$(form)[0].reset();
		},
		formReadonly: function (form, bool) {
			if (bool) {
				$(form).find('input').attr('readonly', true);
				$(form).find('select').attr('disabled', true);
				$(form).find('button').hide();
			} else {
				$(form).find('input').removeAttr('readonly');
				$(form).find('select').removeAttr('disabled');
				$(form).find('button').show();
			}
		},
//修改URL参数

		replaceParamVal: function (paramName, replaceWith, url) {
			if (String(replaceWith).isEmpty()) replaceWith = "";
			var oUrl = url == undefined ? this.location.href.toString() : url;
			var patt1 = /\/[0-9]-[1-9][0-9]/;
			var nUrl = "";
			oUrl = oUrl.indexOf("#") == -1 ? oUrl : oUrl.split("#")[0];
			oUrl = oUrl.replace(patt1, "")
			if (oUrl.indexOf(paramName) != -1) {
				var re = eval('/(' + paramName + '=)([^&]*)/gi');
				nUrl = oUrl.replace(re, paramName + '=' + replaceWith);
			} else {
				nUrl = oUrl.indexOf("?") == -1 ? oUrl + "?" + paramName + "=" + replaceWith : oUrl + "&" + paramName + "=" + replaceWith;
			}
			return nUrl;
		},

		isEmpty: function (str) {
			return str == undefined || str == null || str == '' || str == 'undefined' || str == 'null';
		},
		trim: function (str) {
			if (!str || typeof str != "string") return str;
			return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
		},

		req: function (url, pmara, success, error, meth, type) {
			meth = (meth == undefined || meth == null) ? "GET" : meth;
			//data=( data==undefined||data==null)?{}:data;
			success = (success == undefined || success == null) ? function (x) {
			} : success;
			error = (error == undefined || error == null) ? function (x) {
			} : error;
			type = type ? type : (meth == "GET" || meth == "DELETE" ? "application/x-www-form-urlencoded" : "application/json");
			var time = server.getCache(url + JSON.stringify(pmara));
			if (time != "" && (meth == "POST" || meth == "post") && Number(time) > new Date().getTime()) {
				return;
			}
			server.setCache(url + JSON.stringify(pmara), new Date().getTime() + 3000);
			var that = this;
			$.ajax({
				type: meth,
				url: server.url + url,
				dataType: "json",
				contentType: type,
				data: (meth == "POST" && type == "application/json") ? JSON.stringify(pmara) : pmara,
				success: function (data) {
					if (server.jump[data.code]) {
						let i = window.location.hash.substr(2);
						let u = "";
						if (i && i != "") u = i;
						server.loadindex(server.jump[data.code], "redirectUri=" + u);
					} else {
						success(data);
					}
				},
				beforeSend: function (xhr) {
					//     let token = server.getCache("token");
					let token = that.getCookie('token');
					if (token) {
						xhr.setRequestHeader('token', token);
						that.setCache("token", token);
					}
				},
				error: error
			});

		},

		getCache: function (name) {
			var text = sessionStorage.getItem(name);
			return (!text || server.trim(String(text)) == "") ? "" : server.trim(String(text));
		},
		setCache: function (name, value) {

			window.sessionStorage.setItem(name, value);
		},
		setchatnews: function (name, value) {
			if (value)
				window.localStorage.setItem(name, JSON.stringify(value));
		},
		getchatnews: function (name) {
			var v = window.localStorage.getItem(name);
			if (v)
				try {
					return JSON.parse(v);
				} catch (e) {

				}
			return v;
		},

		getCookie: function getCookie(name) {
			var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
			if (arr = document.cookie.match(reg))
				return unescape(arr[2]);
			else
				return null;
		},

		/**
		 *
		 * 定时执行任务
		 * @param times  时间
		 * @param done   执行完成时执行
		 * @param runing  每过一秒执行
		 */
		autotime: function (times, done, runing) {
			if (times == 0) {
				if (done) done();
				return;
			}
			setTimeout(() => {
				times--;
				this.autotime(times, done, runing);
				if (runing) runing(times)
			}, 1000);
		},
		loadpage: function (u) {
			var time = server.cache_loadindex[u + "_loadpage"];
			if (time && Number(time) > new Date().getTime()) {
				return;
			}
			server.cache_loadindex[u + "_loadpage"] = new Date().getTime() + 1000;

			var xmlhttp;
			//showLoading(5);
			if (window.XMLHttpRequest) {
				xmlhttp = new XMLHttpRequest();
			} else {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			xmlhttp.onreadystatechange = function () {
				if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
					var text = xmlhttp.responseText;
					document.title = server.getStr(text, "<title>", "</title>");
					history.pushState(null, null, null);
					document.getElementById("main_context").innerHTML = text;
					server.loadscript(text);
					//completeLoading();
				}

			}
			var i = window.location.hash.substr(2);

			xmlhttp.open("GET", server.url + ((i != undefined && i != null && i != "") ? i : u) + ".html", true);
			xmlhttp.send();
		},

		getStr: function (str, start, end, n) {
			let res = str.match(new RegExp(`${start}(.*?)${end}`))
			return res ? res[n ? n : 1] : null
		},

		loadscript: function (text) {
//	 setTimeout( ()=>{
			var start = text.indexOf("<script");
			while (start != -1) {
				end = text.indexOf("</script>");
				script = text.substring(start, end);
				var patt = /\s+src=\s*['|"].+['|"]\s+/g;
				var result = patt.exec(script);
				var ii = script.indexOf(">");
				var is = script.indexOf("src=");
				if (!server.isEmpty(String(result)) && ii > is) {
					result = String(result).split("=")[1].replace("\"", "").replace("\"", "").replace("\'", "").replace("\'", "");
					var oHead = document.getElementsByTagName('head')[0]; // 在head标签中创建创建script
					var oScript = document.createElement("script");
					oScript.type = "text/javascript";
					if (result.indexOf("http") == -1) {
						if (result.indexOf("/") == 0) {
							server.host + result;
						} else {
							result = server.url + result;
						}

					}
					oScript.src = result;
					oHead.appendChild(oScript);
				} else {
					script = script.substring(script.indexOf(">") + 1);
					eval(script);
				}
				text = text.substring(end + 9);
				start = text.indexOf("<script");
			}
			//	}, 100);
		},
		cache_loadindex: {},
		loadindex: function (url, params, nothistory) {

			var time = server.cache_loadindex[url + params];
			if (time && Number(time) > new Date().getTime()) {
				return;
			}
			server.cache_loadindex[url + params] = new Date().getTime() + 1000;
			//server.setCache(url + params?"":params+"_loadindex", new Date().getTime() + 1000);

			if (server.notStack[url]) nothistory = true;
			var url2 = server.url + "index.html" + ((params) ? "?" + params : "") + "#!" + url;
			server.Stack.push(url + "-,-" + (params ? params : "") + (!nothistory ? "" : "nothistory"));
			window.history.replaceState(null, null, url2)
			server.loadpage(url)
		},
		lastPage: function () {
			let url = server.Stack.getlast();
			if (url != null) {
				server.Stack.pop();
			} else {
				url = server.Stack.peek();
			}
			if (url) {
				let params = url.split("-,-")[1];
				if (params.indexOf("nothistory") > -1) {
					server.lastPage();
					return;
				}
				let url1 = url.split("-,-")[0];
				;
				var url2 = server.url + "index.html?" + (params ? params : "") + "#!" + url1;
				window.history.replaceState(null, null, url2)
				server.loadpage(url1)
			}
		},
		nextPage: function () {
			window.alert("next");
		},
		getQueryString: function (name, url) {
			var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$|(!#))', 'i');
			var r = null;
			if (!server.isEmpty(url)) {
				r = url.match(reg);
			} else {
				console.log()
				r = window.location.search.substr(1).match(reg);
			}
			if (r != null) {
				return unescape(decodeURIComponent(r[2]));
			}
			return null;
		},

		isIos: function () {
			var u = navigator.userAgent, app = navigator.appVersion;
			//   var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
			var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

			if (isIOS) return true;
			return false;
		},
		getUserInfo: function (f) {

			if (server.getCache("userInfo")) {
				if (f) f(JSON.parse(server.getCache("userInfo")));
				return JSON.parse(server.getCache("userInfo"));
			}
			server.req("wechat/userInfo", {}, function (e) {
				if (e.code == 0)
					server.setCache("userInfo", JSON.stringify(e.data));
				console.log("userinfo1")
				if (f) f(e.data)
				return e.data;
			})
		},
		removeUser: function () {
			server.setCache("userInfo", "");
		},
//关闭微信页面
		weixinClosePage: function () {
			if (typeof WeixinJSBridge == "undefined") {
				if (document.addEventListener) {
					document.addEventListener('WeixinJSBridgeReady', weixin_ClosePage, false);
				} else if (document.attachEvent) {
					document.attachEvent('WeixinJSBridgeReady', weixin_ClosePage);
					document.attachEvent('onWeixinJSBridgeReady', weixin_ClosePage);
				}
			} else {
				weixin_ClosePage();
			}
		},
		getStorageSync: function (name) {
			return window.localStorage.getItem(name);
		},
		setStorageSync: function (name, value) {
			window.localStorage.setItem(name, value);
		},
		stock: {
			maxl: 100,
			key: "stocklist",
			push: (x) => {
				var list;
				if (server.getStorageSync(server.stock.key)) {
					try {
						list = JSON.parse(server.getStorageSync(server.stock.key));
					} catch (e) {
						list = [];
					}
				} else {
					list = [];
				}
				if (!list instanceof Array) {
					list = [];
				}
				if (list.length > server.stock.maxl) {
					list.remove(list[0]);
				}
				if (server.stock.exists(x)) {
					list.remove(x);
				}
				list.push(x);
				server.setStorageSync(server.stock.key, JSON.stringify(list));
				//	console.log( uni.getStorageSync(mqttclient.stock.key))
			},
			exists: (x) => {
				try {
					//console.log(x);
					//console.log(server.getStorageSync(server.stock.key).indexOf(JSON.stringify(x)));
					if (!server.getStorageSync(server.stock.key)) return false;
					//	console.log(server.getStorageSync(server.stock.key).indexOf(JSON.stringify(X)));

					return JSON.parse(server.getStorageSync(server.stock.key)).indexOf(x) > -1;
				} catch (e) {
					//console.log(e)
					//console.log(server.getStorageSync(server.stock.key));
					return false;
				}

				return false;
			},
			getlist: () => {
				var list;
				if (server.getStorageSync(server.stock.key)) {
					try {
						list = JSON.parse(server.getStorageSync(server.stock.key));
					} catch (e) {
						list = [];
					}
				} else {
					list = [];
				}
				if (!list instanceof Array) {
					list = [];
				}
				return list;
			}
		}
	}

	// Array.prototype.indexOf = function (val) {
	// 	for (var i = 0; i < this.length; i++) {
	// 		if (server.arraycompareto(this[i], val)) return i;
	// 	}
	// 	return -1;
	// };
	Array.prototype.remove = function (val) {
		var index = this.indexOf(val);
		if (index > -1) {
			this.splice(index, 1);
		}
	};


	server.arraycompareto = function (x, y) {
// If both x and y are null or undefined and exactly the same
		if (x === y) {
			return true;
		}
// If they are not strictly equal, they both need to be Objects
		if (!(x instanceof Object) || !(y instanceof Object)) {
			return false;
		}
//They must have the exact same prototype chain,the closest we can do is
//test the constructor.
		if (x.constructor !== y.constructor) {
			return false;
		}
		for (var p in x) {
			//Inherited properties were tested using x.constructor === y.constructor
			if (x.hasOwnProperty(p)) {
				// Allows comparing x[ p ] and y[ p ] when set to undefined
				if (!y.hasOwnProperty(p)) {
					return false;
				}
				// If they have the same strict value or identity then they are equal
				if (x[p] === y[p]) {
					continue;
				}
				// Numbers, Strings, Functions, Booleans must be strictly equal
				if (typeof (x[p]) !== "object") {
					return false;
				}
				// Objects and Arrays must be tested recursively
				if (!Object.equals(x[p], y[p])) {
					return false;
				}
			}
		}
		for (p in y) {
			// allows x[ p ] to be set to undefined
			if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) {
				return false;
			}
		}
		return true;
	};
	String.prototype.trim = function () {
//	return this.replace(/^\s+|\s+$/g,"");//js去掉两头空格
		return this.replace(/(^\s*)|(\s*$)/g, "");
	}

	String.prototype.html = function (encode) {
		var replace = ["%2y2;", ".", "%2y1;", "?", "%2y;", "*", "%2z", "|", "%2F", "/", "%2B", "+", "%#39;", "'", "%quot;", '"', "%nbsp;", " ", "%gt;", ">", "%lt;", "<", "%yen;", "¥", "%amp;", "&"];
		var replaceReverse = ["\\.", "%2y2;", "\\?", "%2y1;", "\\*", "%2y;", "\\|", "%2z", "/", "%2F", "\\+", "%2B", "&", "%amp;", "¥", "%yen;", "<", "%lt;", ">", "%gt;", " ", "%nbsp;", '"', "%quot;", "'", "%#39;"];
		var target;
		if (encode) {
			target = replaceReverse;
		} else {
			target = replace;
		}
		for (var i = 0, str = this; i < target.length; i += 2) {
			str = str.replace(new RegExp(target[i], 'g'), target[i + 1]);
		}
		return str;
	};

	function weixin_ClosePage() {
		WeixinJSBridge.call('closeWindow');
	}

	if (location.host.indexOf("www.xuanzhu123.com") > -1) {
		server.context = "/wechat/";
	}

	server.url = server.host + server.context;


	//server.loadindex('index.html#!'+server.index)

	exports('server', server);

})